package com.zgxt.demo.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zgxt.demo.Dao.UserDao;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//拦截器配置类
public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //前置
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setContentType("text/plain"); // 设置内容类型为纯文本
            response.setCharacterEncoding("UTF-8"); // 设置字符编码为UTF-8
            // 不存在,拦截 返回401状态码
            response.setStatus(401);
            JSONObject json = JSONUtil.createObj()
                    .putOpt("msg",401)
                    .putOpt("data", "请先进行登录");
            // 写入提示信息到响应的输出流中，可以根据需要设置具体的提示信息内容
            response.getWriter().write(String.valueOf(json));
            return false;
        }
        //基于token获取redis里的用户信息
        String key = "Food:token:" + token;
        Map<Object,Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        if (userMap.isEmpty()) {
            response.setContentType("text/plain"); // 设置内容类型为纯文本
            response.setCharacterEncoding("UTF-8"); // 设置字符编码为UTF-8
            // 不存在,拦截 返回401状态码
            response.setStatus(401);
            JSONObject json = JSONUtil.createObj()
                    .putOpt("msg",401)
                    .putOpt("data", "用户不存在");
            response.getWriter().write(String.valueOf(json));
        }
        //数据转换为UserDao对象
        UserDao userDao = BeanUtil.fillBeanWithMap(userMap, new UserDao(), false);
        //存在，把信息保存在ThreadLocal里
        UserHolder.setUserDao(userDao);
        // 刷新Redis有效期
        stringRedisTemplate.expire(key, 30L, TimeUnit.MINUTES);
        // 放行
        return true;
    }

    //后置
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //移除用户
        UserHolder.removeUserDao();
    }


}
